#!/bin/bash
#reduction file and result file is automatical made each day.
#if one source is observed at different day. the light curve will be at different files, with the same file name.
#So one need to combine them by hand if needed and being carefull.
#

rm -rf /tmp/*
Dir_now=`pwd`
if [ $# -ne 1  ]
then
    echo "usage: x60cmF_Plus2mass.sh fitfile"
    exit 0
fi
fitfile=$1
#RA=$2
#DEC=$3
errorbar=60 #arcsec
Nobj_least=3  # it is the least obj in the fitfile
SolveRadius=0.3  # degree, for solve-field when doing the AStronomy
Ncompstar_c=3  # the number of comparison stars should be more than this number
ObjEllipForAstro_c=0.23 #The critical value for the average ellipticity for objects in the image. if the value is larger than this value, the image is thought to be bad and this exit this run.
#serchError=44   #25arc,  #120 #it is the dirmeter, this value is the same as one in xcross60cmOT.c
serchError=120   #25arc,  #120 #it is the dirmeter, this value is the same as one in xcross60cmOT.c

#ObjEllipFormatch_c=2.0
#IP_server_local=190.168.1.118:8080/gwac
#IP_server=190.168.1.25
IP_server=172.28.8.8:8080/gwebend
UploadParameterfile=` echo "http://$IP_server/otFollowUpload.action" | awk '{print($1)}'`
Monitorfile=$HOME/workspace/monitor.log
fieldAstrometryCaliFile=$HOME/workspace/fieldAstroCaliFile
stringtimeForMonitorT=`date -u +%Y%m%d`
dir_reduction=$HOME/workspace/reduction/$stringtimeForMonitorT
dir_result=$HOME/workspace/result/$stringtimeForMonitorT
dir_soft60cm=$HOME/software/soft60cm
cd $HOME/workspace/reduction
if test ! -r $stringtimeForMonitorT
then
    echo "making $stringtimeForMonitorT"
    mkdir $stringtimeForMonitorT
fi
cd $HOME/workspace/result
if test ! -d $stringtimeForMonitorT
then
    echo "making $stringtimeForMonitorT in result"
    mkdir $stringtimeForMonitorT
fi
cd $Dir_now
if test ! -r $fitfile
then
    echo "No $fitfile"
    exit 0
fi
cp $fitfile $dir_reduction
cp $dir_soft60cm/* $dir_reduction
cd $dir_reduction

xdefineForCatalog (  )
{
#    echo `pwd`
    #dir_getCatalog=$HOME/han/catalogue
    dir_getCatalog=$HOME/han/catalogue_v1.2
    
    RadiusTemp_2mass=3.0   #10.0  for GRB, 3.0 for the GWAC, #minitus for 2mass 
    RadiusTemp=0.6   #degree for usno
    lowMagTemp=-10.0    #brightest object
    largerMagTemp=23.0  #dimest object
    dir_usnob10=$HOME/usnob10
}


xdefineForFits (  )
{
#    echo `pwd`

    AstroCaliFile=`echo $fitfile | sed 's/\.fit/.new/g'`
    OUTPUT=`echo $fitfile | sed 's/\.fit/.sex/g'`
    OUTPUT_limit=`echo $fitfile | sed 's/\.fit/.sex_limit/g'`
    OUTPUT_limit_new=`echo $fitfile | sed 's/\.fit/.sex_new_limit/g'`
    OTfinalres_limit=`echo $fitfile | sed 's/\.fit/_otfinalres_withlimit.txt/g'`
    prefix=`echo $fitfile | sed 's/\.fit//g'`
    OUTPUT_new=`echo $fitfile | sed 's/\.fit/.sexnew/g'`
    TempUSNORADEC=`echo $fitfile | sed 's/\.fit/_tempRADEC.txt/g'`
    TempUSNOXY=`echo $fitfile | sed 's/\.fit/_tempXY.txt/g'`
    otxy=`echo $fitfile | sed 's/\.fit/_otxy.txt/g'`
    MonitorFile=`echo $fitfile | sed 's/\.fit/_res.txt/g'`
    matchedfile=`echo $fitfile | sed 's/\.fit/_KnownObjxy.txt/g'`
    compstarsfile=`echo $fitfile | sed 's/\.fit/_compstars.txt/g'`
    OTfile=`echo $fitfile | sed 's/\.fit/_otrealxy.txt/g'`
    checkstarfile=`echo $fitfile | sed 's/\.fit/_checkstarrealxy.txt/g'`
    deltaMagfile=`echo $fitfile | sed 's/\.fit/_deltaMag.txt/g'`
    OTfinalres_withdis=`echo $fitfile | sed 's/\.fit/_otfinalres_withdis.txt/g'`
    OTfinalres=`echo $fitfile | sed 's/\.fit/_otfinalres.txt/g'` 
    OTfinalresDiscal=`echo $fitfile | sed 's/\.fit/_otfinalresDisCal.txt/g'`
    OTFieldxyForTvMark=`echo $fitfile | sed 's/\.fit/_otxyfortvmark.txt/g'`
    OTFieldxy=`echo $OTid | awk '{print($1".otxy")}'`
    OTTriggerxy=`echo $OTid | awk '{print($1"_trigger.otxy")}'`
    OTFieldxy_ref=`echo $OTid | awk '{print($1".otxyref")}'`
    OTFieldTemp=`echo $OTid | awk '{print($1".tempcomp")}'`
    OTFieldUSNO=`echo $OTid | awk '{print($1".tempusno")}'`
    miniOT_lc=`echo $OTid | awk '{print($1"_miniOT.lc")}'`
    newOT_lc=`echo $OTid | awk '{print($1"_newOT.lc")}'`
    CATAS_lc=`echo $OTid | awk '{print($1"_CATAS.lc")}'`
    CHECK_lc=`echo $OTid | awk '{print($1"_CHECK.lc")}'`
    OTWCSfit=`echo $OTid | awk '{print($1"_wcs.new.fit")}'`
    Temp2massXY_Jmag=`echo $OTid |  awk '{print($1"_2massXY_Jmag.txt")}'`
    Temp2massXY_Kmag=`echo $OTid |  awk '{print($1"_2massXY_Kmag.txt")}'`
    Temp2massXY_JKmag=`echo $OTid |  awk '{print($1"_2massXY_JKmag.txt")}'`
    2massJcatalog_radec=`echo $OTid | awk '{print($1"_2mass.radec")}'`
    2massJcatalog_xy=`echo $OTid | awk '{print($1"_2mass.xy")}'`
    

}

xastronomy (  )
{
#    echo "To do the xastronomy"
#    echo `pwd`
     echo $fitfile
	echo `pwd` 
    rm -rf *.axy *objs-png
#    solve-field --use-sextractor -scale -H 0.7 -L 0.2 -u app -3 $RA -4 $DEC -5 $SolveRadius $fitfile   
    solve-field -O -p --use-sextractor -scale -H 0.58 -L 0.53 -u app -3 $RA -4 $DEC -5 $SolveRadius $fitfile #
    wait
    if test -r $AstroCaliFile
    then
       echo "AStronomy calibration is successful"
       cp $AstroCaliFile $OTWCSfit
       cp $OTWCSfit $fieldAstrometryCaliFile 
    else
        echo "Astronomy calibration failed, try another image please"
        echo $Dir_now
        exit 0
    fi

}

xastronomy_others ( )
{
    echo "xastronomy_others"
    echo $fitfile
    AstroCaliFile=`echo $fitfile | sed 's/\.fit/.new/g'`
    RATT=`gethead $fitfile "objctra"`
    DECTT=`gethead $fitfile "objctdec"`
    SolveRadiusT=1

    solve-field -O -p --use-sextractor -scale -H 0.58 -L 0.53 -u app -3 $RATT -4 $DECTT -5 $SolveRadiusT $fitfile
    wait
    if test -r $AstroCaliFile
    then
        rm -rf $fitfile
        mv $AstroCaliFile $fitfile
    fi
}

xGetCatalog (  )
{
   echo "xGetCatalog"
    cd $dir_reduction
#    echo "~/usnob10/src/usnob1 -R $dir_usnob10 -c $RA $DEC  -r 25 -lmr2 0,23 -m 2000000 -sr >listusnobobj"
    echo "~/usnob10/src/usnob1 -R $dir_usnob10 -c $RA $DEC  -r 25 -lmr2 0,23 -m 2000000 -sr"
    ~/usnob10/src/usnob1 -R $dir_usnob10 -c $RA $DEC  -r 25 -lmr2 0,23 -m 2000000 -sr >listusnobobj
    
    python $dir_usnob10/xusnob10_format.py ./ listusnobobj
    echo "deltayear=$deltayear"
    #msec --->deg    /3600/1000
    #deg--->rad
    echo "=========tmp_listusnobobj====="
    head -1 tmp_listusnobobj
    cat tmp_listusnobobj | awk '{print($1+$7*deltayear/cos($2*3.1415926/180)/3600/1000,$2+$8*deltayear/3600/1000,$3,$4,$5,$6)}' deltayear=$deltayear > $TempUSNORADEC
    #cat tmp_listusnobobj | awk '{print($1,$2,$3,$4,$5,$6)}' deltayear=$deltayear > $TempUSNORADEC
    cp tmp_listusnobobj aold.txt
    #output includes ra dec b1 b2 R1 R2 I

#    ~/usnob1/usnob1 -m 2000000  -r 0.3 -c $RA $DEC -lmr -6,20 -sr > $TempUSNORADEC
    if test -s $TempUSNORADEC
    then
        echo "Geting catalog is successful"
	wc $TempUSNORADEC
    else
        echo "Geting catalog failed"
        echo $Dir_now
        exit 0
    fi
}

xGetCatalog_temp_2mass ( )
{
    echo "xGetCatalog_temp_2mass"
    cd $dir_getCatalog
    echo $dir_getCatalog
    rm 2massoutput 
    python 2mass_db_search.py $RA $DEC -b $RadiusTemp_2mass  2massoutput
	echo "2massoutput"
    mv 2massoutput $dir_reduction 
	cd $dir_reduction

}

xGetCatalog_temp (  )
{
    echo "xGetCatalog_temp"
    cd $dir_reduction
    rm temp*.txt 
    cd $dir_getCatalog
    echo $dir_getCatalog  
    
    echo "python template_extract_60cm.py $dir_reduction $RA $DEC $RadiusTemp $lowMagTemp $largerMagTemp"
    python template_extract_60cm.py $dir_reduction $RA $DEC $RadiusTemp $lowMagTemp $largerMagTemp
    wait
    if test -s $dir_reduction/temp*.txt
    then
        echo "Catalog is ready"
        
        cd $dir_reduction
        cat temp*.txt | awk '{print($1+$7*deltayear/cos($2*3.1415926/180)/3600/1000,$2+$8*deltayear/3600/1000,$3,$4,$5,$6)}' deltayear=$deltayear > $TempUSNORADEC
	#mv temp*.txt $TempUSNORADEC
	
        #The parameters in $TempUSNORADEC are RA DEC B1 B2 R1 R2
    else
        echo "Catalog is not ready"
        cd $Dir_now
        exit 0
    fi
}


xdisplayOTandnewImg ( )  
{
    echo "xdisplayOTandnewImg"
    ds9_num=`ps -all | grep "ds9" | wc -l`
    if [ $ds9_num -gt 0  ] 
    then   
        :
    else
        ds9 &
        wait
    fi  
    if test -r $OTWCSfit
    then
        cp $OTWCSfit temp.fit
    else
        cp $fitfile temp.fit
    fi
    echo `date` "display temp and new image and tvmark these OTc1"
	echo $Temp2massXY_Jmag $Temp2massXY_Kmag
	echo "=============="

    cd $HOME/iraf
    cp -f login.cl.old login.cl
    echo noao >> login.cl
    echo digiphot >> login.cl
    echo image >> login.cl
    echo imcoords >>login.cl
    echo "cd $dir_reduction" >> login.cl
    echo "display(image=\"$fitfile\",frame=1)" >>login.cl #display newimage in frame 1
    echo "display(image=\"temp.fit\",frame=2)" >>login.cl #display temp image in frame 1
    echo "display(image=\"temp.fit\",frame=3)" >>login.cl #display temp image in frame 3 for 2mass catalog
    echo "display(image=\"temp.fit\",frame=4)" >>login.cl #display temp image in frame 3 for 2mass catalog
    echo "tvmark(frame=2,coords=\"$OTFieldxy_ref\",mark=\"circle\",radii=5,color=205,label-)" >>login.cl # tvmark OT in ref frame 2
    echo "tvmark(frame=2,coords=\"$OTTriggerxy\",mark=\"circle\",radii=$serchError,color=207,label+,nxoffse=-30,nyoffse=50,txsize=1)" >>login.cl # tvmark OT in ref frame 2
    echo "tvmark(frame=2,coords=\"$OTFieldxyForTvMark\",mark=\"circle\",radii=5,color=204,label+, nxoffse=5,nyoffse=5,txsize=1)" >>login.cl # tvmark new OT in frame 2
    echo "tvmark(frame=3,coords=\"$Temp2massXY_Jmag\",mark=\"circle\",radii=5,color=205,label+, nxoffse=5,nyoffse=5,txsize=1)" >>login.cl # tvmark 2mass catalog in frame 3 for humman check.
    echo "tvmark(frame=4,coords=\"$Temp2massXY_Kmag\",mark=\"circle\",radii=5,color=205,label+, nxoffse=5,nyoffse=5,txsize=1)" >>login.cl # tvmark 2mass catalog in frame 3 for humman check.
    echo "tvmark(frame=4,coords=\"$TempUSNOXY\",mark=\"circle\",radii=3,color=204,label-, nxoffse=5,nyoffse=5,txsize=1)" >>login.cl
    echo logout >> login.cl
    cl < login.cl>xlogfile
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    cd $Dir_redufile
    rm temp.fit
    date
    echo " red  circle is for the new image xy in reference frame"
    echo "green circle is for the ref image xy in reference frame"
}


xGetkeywords (  )
{
    echo `pwd`
    echo "xGetkeywords"
    datetime=`gethead $fitfile "date-obs"`
    OTid=`gethead $fitfile "object"`
    OTid_Follow=`gethead $fitfile "RUN_TIME"`
    OTsource=`echo $OTid | cut -c1-1`
    FTid=`gethead $fitfile "telescope" `    #follow-up telescope id
    exptime=`gethead $fitfile "exptime"`
    filter=`gethead $fitfile "filter"` #default is R filter right now
    RAT=`gethead $fitfile "objctra"`
    DECT=`gethead $fitfile "objctdec"`
    JD=`gethead $fitfile "jd"`
    deltayear=`echo $JD | awk '{print(($1-2451545.0)/365.25)}'`
    CCDTYPE=`gethead $fitfile "ccdtype"` #BIAS, DARK, FLAT, LIGHT, FOCUS
    FTid=F01  #west 60cm telescope is F01 and east 60cm isn F02
    #echo "==============="
    #echo "OTid_Follow=$OTid_Follow ,  OTid=$OTid"
    #OTid=`echo $OTid_Follow | cut -c1-14`
    #echo "RAT=$RAT DECT=$DECT" 
    RA=`skycoor -d $RAT $DECT | awk '{print($1)}'`
    DEC=`skycoor -d $RAT $DECT | awk '{print($2)}'`
    
    CCDNumber=`gethead $fitfile "OBSERVER"  | cut -c3-3` 
    echo $CCDNumber
    if [ $CCDNumber -lt 5  ]
    then
	serchError=44
	ccd_term=jfov
     else
	ccd_term=ffov
     fi
     echo "ccd_term=$ccd_term"
        
    if [ "$OTsource"x = "M"x ]
    then
	IP_server=190.168.1.25
	UploadParameterfile=` echo "http://$IP_server/otFollowUpload.action" | awk '{print($1)}'`
    fi

    echo $datetime $OTid $FTid $exptime $filter $RA $DEC $JD $CCDTYPE
    echo $RA $DEC 

   CCDsize=`gethead $fitfile "NAXIS1" | awk '{print($1)}'`	
   #CCDsize=1024.0 # for 60cm
   #CCDsize=2048.0  #for 50cm
   CCDcenter=`echo $CCDsize | awk '{print($1/2)}'`
   ejmin=20.0
   ejmax=`echo $CCDsize $ejmin | awk '{print($1-$2)}'`
}

xsethead (  )
{
    
    newfitfile=`echo $fitfile | sed 's/\.fits/.fit/g'`
    cp $fitfile  $newfitfile
    echo $newfitfile
    fitfile=`echo $newfitfile`
    echo $fitfile
    OTidname=`echo $fitfile | cut -c1-14`
    sethead -kr X object=$OTidname telescope=WFT  filter=R objctra=$RA objctdec=$DEC jd=50000 CCDTYPE=LIGHT $fitfile

}

xsky2xyOT (  )
{
    #sky2xy $AstroCaliFile $RA $DEC >fotxy
    sky2xy $OTWCSfit $RA $DEC >fotxy
    cat fotxy | grep -v "off" | awk '{if($5>0 && $5<CCDsize && $6>0 && $6<CCDsize) print($5,$6,$1,$2,"miniOT")}' CCDsize=$CCDsize | column -t >$otxy   #in $otxy, the parameters are x y ra dec,miniOT
    if test -s $otxy
    then
        echo "The position of ot is in the FOV of the image"
        cat $otxy
        cat $otxy | awk '{print($1,$2,"D="2*serchError"_pixel")}' serchError=$serchError >$OTTriggerxy
    else
        echo "OT is not in the FOV"
        echo $Dir_now
	echo "The position of ot is not in the FoV of the image, should check the pointing of the telescope"
        exit 0
    fi
}

xsky2xyTemp_2mass ( )
{
    echo "xsky2xyTemp_2mass "
    sky2xy $OTWCSfit @2massoutput >tempxy2mass
    #paste tempxy2mass 2massoutput | grep -v "off" | awk '{if($6>0 && $6<1024 && $7>0 && $7<1024)print($6,$7,"J"$3"_H"$4"_K"$5,$1,$2)}' | column -t >$Temp2massXY
    paste tempxy2mass 2massoutput | grep -v "off" | awk '{if($5>0 && $5<CCDsize && $6>0 && $6<CCDsize)print($5,$6,"J"$9,$1,$2)}' CCDsize=$CCDsize | column -t >$Temp2massXY_Jmag
    paste tempxy2mass 2massoutput | grep -v "off" | awk '{if($5>0 && $5<CCDsize && $6>0 && $6<CCDsize)print($5,$6,"K"$11,$1,$2)}' CCDsize=$CCDsize | column -t >$Temp2massXY_Kmag
	paste tempxy2mass 2massoutput | grep -v "off" | awk '{if($5>0 && $5<CCDsize && $6>0 && $6<CCDsize)print($5,$6,$9,$11,$1,$2)}' CCDsize=$CCDsize | column -t >$Temp2massXY_JKmag

    #rm 2massoutput tempxy2mass 
    mv tempxy2mass $2massJcatalog_radec
    mv 2massoutput $2massJcatalog_xy
    ls $2massJcatalog_radec $2massJcatalog_xy

    #sleep 5
       	
    cp $Temp2massXY_Jmag $Temp2massXY_Kmag  $2massJcatalog_radec $2massJcatalog_xy $Temp2massXY_JKmag $fieldAstrometryCaliFile 
}

xsky2xyTemp(  )
{
    rm tempxy
   # sky2xy $AstroCaliFile @$TempUSNORADEC >tempxy
    sky2xy $OTWCSfit @$TempUSNORADEC >tempxy
	wc tempxy 
   echo "$TempUSNORADEC"  
   paste tempxy $TempUSNORADEC | grep -v "off" | awk '{if($5>0 && $5<CCDsize && $6>0 && $6<CCDsize)print($5,$6,$7,$8,$9,$10,$11,$12,"99")}' CCDsize=$CCDsize >$TempUSNOXY   #Depend on the parameters after the xGetkeywords. The final parameters are:    x,y, ra, dec, B1, B2,R1,R2,99
    if test -s $TempUSNOXY
    then
        echo "xsky2xy is finished"
        xy2sky $OTWCSfit  $CCDcenter $CCDcenter  >center.txt
        RA_center=`cat center.txt | awk '{print($1)}'`
        DEC_center=`cat center.txt | awk '{print($2)}'`
        PointError=`skycoor -r $RA  $DEC $RA_center $DEC_center | awk '{print($1/60)}'`  #arcmin
        echo $RA $DEC $RA_center $DEC_center $PointError >>$MonitorFile
    else
        echo "No any source after the xsky2xy"
        echo $Dir_now
        exit 0
    fi
}

xcheckimagequality (  )
{
    cat $OUTPUT_new | sort -n -k 3 | head -20 | tail -10 | awk '{print($5)}' >checkimagequality.lst
    head -1 $OUTPUT_new
   # cat checkimagequality.lst
   # echo "------------"
    sumEllValue=0.0
    N_ellipValue=`wc -l checkimagequality.lst | awk '{print($1)}'`
    for ellipValue in `cat checkimagequality.lst | awk '{print($1)}'`
    do
       echo $ellipValue
        sumEllValue_temp=`echo $ellipValue  $sumEllValue | awk '{print($1+$2)}'` 
        sumEllValue=`echo $sumEllValue_temp`
    done
    AverageEllipValue=`echo $sumEllValue $N_ellipValue | awk '{print($1/$2)}'`
    echo "`date` $fitfile AverageEllipValue=$AverageEllipValue" >>$Monitorfile
    
    echo "sumEllValue=$sumEllValue  N_ellipValue=$N_ellipValue  AverageEllipValue=$AverageEllipValue"
    if [ ` echo " $AverageEllipValue > $ObjEllipForAstro_c " | bc ` -eq 1  ]  
    then
       xdisplayOTandnewImg
       echo "This image is not good, pls try next image." 
       exit 0
    else
        echo "This image is good enough"
    fi

}


xGetstars (  )
{
    echo `pwd`
#    echo $fitfile
#    ls $fitfile
#    echo $OUTPUT
    Detect_sigma=1.5
    sex $fitfile  -c  daofind.sex  -DETECT_THRESH $Detect_sigma -ANALYSIS_THRESH $Detect_sigma -CATALOG_NAME $OUTPUT
    #cat $OUTPUT | awk '{if($1>ejmin && $2>ejmin && $1<ejmax && $2<ejmax && $4<0.3 && $7>2.0 && $5<0.4)print($0)}' ejmin=$ejmin  ejmax=$ejmax >temp
    cp $OUTPUT $OUTPUT_limit
    cat $OUTPUT | awk '{if($1>ejmin && $2>ejmin && $1<ejmax && $2<ejmax && $4<0.3 && $7>2.0)print($1,$2,$3,$4,$5,$6,$7,$8)}' ejmin=$ejmin  ejmax=$ejmax >temp
    cat temp | awk '{if($6>0.7 || $6==0.7)print($0)}' >temp1
    cat temp | awk '{if($6<0.7 && $5<0.5)print($0)}' >>temp1	
    mv temp1 $OUTPUT
    rm -rf temp
    Nobj=`wc -l $OUTPUT | awk '{print($1)}'`

    if [ $Nobj -gt $Nobj_least  ]
    then
        echo "$fitfile has $Nobj stars "
        cp $OUTPUT $OUTPUT_new
        xcheckimagequality 
    #    ls $OUTPUT_new
    #    cat $OUTPUT_new
    else
        echo "Only $Nobj stars in the $fitfile, please try another image or increase the exptime"
        xdisplayOTandnewImg
        echo $Dir_now
        exit 0
    fi
    #wc $OUTPUT
    #cat $OUTPUT | awk '{if($5<(1.0*ObjEllipForAstro_c) || $4<0.05 )print($0)}' ObjEllipForAstro_c=$ObjEllipForAstro_c >temp	
    #mv temp $OUTPUT_new
    #wc $OUTPUT_new

}

xcopyResultTobakfile (  )
{
    #cp $OTfinalres $miniOT_lc $newOT_lc $CATAS_lc $CHECK_lc $OTFieldTemp  $compstarsfile  $dir_result
    cp  $miniOT_lc $newOT_lc $CATAS_lc $CHECK_lc  $dir_result

}

xCalcuShiftandVariable (  )
{
    lc_list=$1
    if test  -s $lc_list
    then
        N_lc_list=`cat $lc_list | wc -l | awk '{print($1)}'` 
        if [ $N_lc_list -lt 2   ]
        then
            echo "DeltaXY=0.00 pixel ; DeltaMag=0.00 mag in 0.00 sec "
        else
            head -1 $lc_list | awk '{print($1,$4,$5,$6,$7,$8,$9)}' >temp_lclist
            tail -1 $lc_list | awk '{print($1,$4,$5,$6,$7,$8,$9)}' >>temp_lclist
            cat temp_lclist | tr '\n' ' '  >temp_lclist1
            DeltaTime=`cat temp_lclist1 | awk '{printf("%.2f",($8-$1)*86400)}'`
            DeltaXY=`cat temp_lclist1 | awk '{printf("%.2f",sqrt(($11-$4)*($11-$4)+($12-$5)*($12-$5)))}'`
            DeltaMag=`cat temp_lclist1 | awk '{printf("%.2f",$13-$6)}'`
            
            echo "DeltaXY=$DeltaXY pixel ; DeltaMag=$DeltaMag mag in $DeltaTime sec "
        
            rm -rf temp_lclist temp_lclist1 
        fi
    fi
}

xgetlc (  )
{
    #cat $OTfinalres
    #echo "before grep"
    #cat $miniOT_lc $newOT_lc $CATAS_lc
    cat $OTfinalres | grep "miniOT" >>$miniOT_lc
    cat $OTfinalres | grep "newOT" >>$newOT_lc
    cat $OTfinalres | grep "CATAS" >>$CATAS_lc
    cat $OTfinalres | grep "CHECK" >>$CHECK_lc
   
    #echo "before sort and uniq"
    #cat $miniOT_lc $newOT_lc $CATAS_lc
    
    sort -n -k 19 $miniOT_lc | uniq >lctemp
    mv lctemp $miniOT_lc
    sort -n -k 19 $newOT_lc | uniq >lctemp
    mv lctemp $newOT_lc
    sort -n -k 19 $CATAS_lc | uniq >lctemp
    mv lctemp $CATAS_lc
    sort -n -k 19 $CHECK_lc | uniq >lctemp
    mv lctemp $CHECK_lc

    echo "            "
    echo "for $fitfile : "
    #cat $OTfinalres
    echo "------------------------"
    echo "For the first and last obs:"
    echo "Any changes of X Y (delta>3.0. line 6 and 7) indicats a moving obj"
    echo "Any changes of Mag (delta>0.1, line 8 and 9) indicats a variables "
    cat $OTfinalres | while read line
    do
        starnum=`echo $line | awk '{print($19)}'`
        OTtype_new=`echo $line | awk '{print($17)}'`
        if [ "$OTtype_new" == "miniOT"  ]
        then
            echo "            "
            echo "miniOT"
            cat $miniOT_lc | awk '{if($19==starnum)print($0)}' starnum=$starnum >lctemp
            head -1 lctemp
            tail -1 lctemp
            xCalcuShiftandVariable lctemp
        elif [ "$OTtype_new" == "newOT"   ]
        then
            echo "            "
            echo "newOT"
            cat $newOT_lc | awk '{if($19==starnum)print($0)}' starnum=$starnum >lctemp
            head -1 lctemp
            tail -1 lctemp
            xCalcuShiftandVariable lctemp
        elif [ "$OTtype_new" == "CATAS"    ] 
        then
            echo "            "
            echo "CATAS"
            cat $CATAS_lc | awk '{if($19==starnum)print($0)}' starnum=$starnum >lctemp
            head -1 lctemp
            tail -1 lctemp
            xCalcuShiftandVariable lctemp
        elif [ "$OTtype_new" == "CHECK"    ] 
        then
            echo "            "
            echo "CHECK"
            cat $CATAS_lc | awk '{if($19==starnum)print($0)}' starnum=$starnum >lctemp
            head -1 lctemp
            tail -1 lctemp
            xCalcuShiftandVariable lctemp
        else
            :
        fi
    done

    echo "-----------------------"
}

xUpdateOTtemp (  )
{

    #cp $TempUSNOXY $OTFieldTemp
    # in $OTFieldxy:   x y ra dec B2 R2 I ottype Obj_label
    cat $OTfinalres | awk '{print($6,$7,$4,$5,$14,$15,$16,$17,$19)}' >$OTFieldxy
    cat $OTfinalres | grep "miniOT" | awk '{print($6,$7,$17)}' >$OTFieldxyForTvMark
    if test -s $OTFieldxyForTvMark
    then
        echo "Only display miniOT candidates"  
        cat $OTfinalres | grep  "CHECK" | awk '{print($6,$7,$17"_"$8-$15)}' >>$OTFieldxyForTvMark
    else
        echo "NO any miniOT"
        cat $OTfinalres | grep "newOT" | awk '{print($6,$7,$17)}' >>$OTFieldxyForTvMark
        cat $OTfinalres | grep -v "newOT" | awk '{print($6,$7,$17"_"$8-$15)}' >>$OTFieldxyForTvMark
        #$8-$15 is deltamag brighterning
    fi
    cp $OTFieldxy $fieldAstrometryCaliFile

}

xCallimit ( )
{
	echo "xCalilimit"
	limit_sigma=3.0
	Gain=2.0   #e-/ADU
	Readnoise=8.0 #e-
	xcheck=`cat $OTfinalres | awk '{if($17=="CHECK")print($6)}'`
	ycheck=`cat $OTfinalres | awk '{if($17=="CHECK")print($7)}'`
	mag_check=`cat $OTfinalres | awk '{if($17=="CHECK")print($8)}'`
	echo $xcheck $ycheck
	#cat $OUTPUT_limit_new
	#sky_check=`cat $OUTPUT_limit | awk '{if(($1-xcheck)>-5 && ($1-xcheck)<5 && ($2-ycheck)>-5 && ($2-ycheck)<5)print($9)}' xcheck=$xcheck  ycheck=$ycheck `
	if test ! -s $OUTPUT_limit_new
	then
		cp $OUTPUT_limit $OUTPUT_limit_new
	fi
	flux_check=`cat $OUTPUT_limit_new | awk '{if(($1-xcheck)>-5 && ($1-xcheck)<5 && ($2-ycheck)>-5 && ($2-ycheck)<5)print($10)}' xcheck=$xcheck  ycheck=$ycheck `
        threshold=`cat $OUTPUT_limit_new | awk '{if(($1-xcheck)>-5 && ($1-xcheck)<5 && ($2-ycheck)>-5 && ($2-ycheck)<5)print($11)}' xcheck=$xcheck  ycheck=$ycheck `
	sigma_sky=`echo $threshold $Detect_sigma | awk '{print($1/$2)}'`
	sky_check=`echo $sigma_sky | awk '{print($1*$1)}'`
	#photometry radius=8 so area=3.1415926*8*8 pixel
	phot_area=`echo 3.1415926 8 | awk '{print($1*$2*$2)}'`
	#noise_faint_object=`echo $phot_area $sky_check $Gain $Readnoise | awk '{print($1*($2*$3+$4*$4))}'`
	noise_faint_object=`echo $phot_area $sky_check $Gain | awk '{print($1*$2*$3)}'`
	#x0=(-b+/-(b^2-4ac))/2a  
	flux_faint_object=`echo $noise_faint_object $limit_sigma | awk '{print(($2*$2+($2**(4)+4*$1*$2*$2)**(0.5))/2)}'`
	limit_mag=`echo $mag_check  $flux_check $flux_faint_object | awk '{printf("%.2f\n",$1+2.5*log($2/$3)/log(10))}'`
	echo "limit_sigma=$limit_sigma Gain=$Gain Readnoise=$Readnoise xcheck=$xcheck ycheck=$ycheck flux_check=$flux_check sky_check=$sky_check mag_check=$mag_check phot_area=$phot_area noise_faint_object=$noise_faint_object flux_faint_object=$flux_faint_object limit_mag=$limit_mag"
	echo "limit_mag=$limit_mag"
	echo "limit_mag=$limit_mag" >$OTfinalres_limit



}


xgetInfor_OT (  )
{
   echo "xgetInfor_OT"
    #to get the light curve, ra dec, picture for identify, comparison objects  of OT,
    #output is $OTfinalres

    if test -s $OTfile
    then
        echo "Detected some objects in this image"
        echo $deltaMagfile
        cat $deltaMagfile

        Ncomp=`wc -l $deltaMagfile | awk '{print($1)}'`
        echo $Ncomp  $filter
        if [ $Ncomp > 0 ]
        then
            if [ "$filter"x == "R"x ] || [  "$filter"x == "Lum"x  ]   #Lum is white filter 
            then
                echo "$filter band"
                delMag_filter=`cat $deltaMagfile | awk '{print($1-$3)}'`
                #cat $deltaMagfile | awk '{print($1-$3)}' >delMagfileCali 
            elif [ "$filter"x == "B"x ]
            then
                echo "$filter band"
                delMag_filter=`cat $deltaMagfile | awk '{print($1-$2)}'`
                #cat $deltaMagfile | awk '{print($1-$2)}' >delMagfileCali
            elif [ "$filter"x == "I"x ]
            then
                echo "$filter band"
                delMag_filter=`cat $deltaMagfile | awk '{print($1-$4)}'`
                #cat $deltaMagfile | awk '{print($1-$4)}' >delMagfileCali
            else
                echo "$filter band"
                delMag_filter=`cat $deltaMagfile | awk '{print($1-($2+$3)/2)}'`
                #cat $deltaMagfile | awk '{print($1-($2+$3)/2)}' >delMagfileCali 
                #(B+V)/2 for other filter expect for B,R,I in usnob1.0
            fi
        
            Notdetection=`wc -l $OTfile | awk '{print($1)}'`
            for((i=0; i<$Notdetection; i++))
            do
                echo $delMag_filter >>delMagfileCali
            done
            xy2sky -d $OTWCSfit @$OTfile >miniOT_RADEC.cat
            head -1 miniOT_RADEC.cat 
            cat  $OTfile  | column -t
            head -1 delMagfileCali
            paste miniOT_RADEC.cat $OTfile delMagfileCali | awk '{if($6>ejmin && $7>ejmin && $6<ejmax && $7<ejmax) print(jd,datetime,filter,$1,$2,$6,$7,$8-$19,$9,$10,$11,$12,$13,$14,$15,$16,$17,fitfile,$18)}' ejmax=$ejmax ejmin=$ejmin jd=$JD  datetime=$datetime filter=$filter  fitfile=$fitfile | sort -n -k  19 | uniq | column -t >$OTfinalres
	   rm -rf DistanceOTc.lst
	   cat $OTfinalres | while read lineotfinalres
  	   do
		RA_OT=`echo $lineotfinalres | awk '{print($4)}'`
		DEC_OT=`echo $lineotfinalres | awk '{print($5)}'`
		skycoor -r $RA_OT $DEC_OT $RA $DEC >>DistanceOTc.lst
	   done
	   echo "======="	
	   paste $OTfinalres DistanceOTc.lst  | sort -n -k 20 >$OTfinalres_withdis
           
    	   cat $OTfinalres_withdis | column -t > $OTfinalres
	   mv DistanceOTc.lst $OTfinalresDiscal
	   
	   xCallimit
	  
	
	   # to get the detection limit
		
   #         head -1 $OTfinalres
            #output have 19 parameters, 
            #they are: jd datetime filter ra dec x y Mag_calibrated_To_usno merr ellipticity  calss_stars fwhm  flag  B2 R2 I OTtype fitfilename,Obj_label 
            rm miniOT_RADEC.cat delMagfileCali
            
   		 echo "YES YES YES YES YES YES"
   		 echo "miniOT is for the mini-detected OT"
   		 echo "newOT is for the OT which is not in the errorbars of mini-detected OT. Might be a moving obj or a real astro obj"
   		 echo "CATAS is in the errorbars and matches usno,Might be a flare star or a SN"
   		 echo "NO_OT means no any possible transient  outside the errorbar and no any object in the errorbar "
   		 echo "         "
   		 echo "   RA        DEC      X_temp    Y_temp    Mag_caliedR2 Merr MagUsnoB2 MagUsnoR2  MagUsnoI OTtype  fitsname  Obj_label"
   		 #cat $OTfinalres | awk '{print($4,$5,$6,$7,$8,$9,$14,$15,$16,$17,$18,$19)}' | column -t

            
            #========================================
            xgetlc
            xcopyResultTobakfile
            xUpdateOTtemp          
            #========================================
        else
            echo "No comparison objects with S/N >10, this image is bad "
            echo $Dir_now
            exit 0
        fi
    
    else
    
        echo "NO NO NO NO NO NO NO"
        echo "No any new objects are detected"
        echo "NO NO NO NO NO NO NO"
        
        echo "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 NO_OT $fitfile 0" >$OTfinalres
    
    fi
    #===========================
    xUploadResult
    #xReducSameField
    #===========================
}

xcrossmatchFor60cmOT_lc(  ) #for the other images 
{
    echo "==========xcrossmatchFor60cmOT_lc====="
    pwd
    cp $OUTPUT_new newimage.cat
    N_compstars=`cat $OTFieldTemp | wc -l | awk '{print($1)}'`
    if [ $N_compstars -gt $Ncompstar_c  ]
    then
        echo "compstars num is larger enough"
        cp $OTFieldTemp refcomp.cat
        #cat $OTFieldTemp | awk '{print($1,$2,$11,$12,$13,$14,$15,$16,$17)}'>refcomp.cat   #$1 $2 are the x and y of the image. and others are from catalogues
    else
        echo "compstars num is too small"
        #cat $OTFieldUSNO | sort -n -k 8 | head -10 | awk '{print($9,$10,$11,$12,$13,$14,$15,$16,$17)}'>refcomp.cat
        cat $OTFieldUSNO | awk '{if($8<18 && $8>0)print($0)}' | sort -n -k 8 | head -10 > $OTFieldTemp
        #cp $OTFieldUSNO refcomp.cat
        echo "=============="
    fi
    cp $OTFieldUSNO refusno.cat
    #cat $OTFieldUSNO
    cp $OTFieldxy otcoord.cat  #output are x y ra dec B2 R2 I miniOT/CATAS/newOT  Obj_label


    echo "To get the OT for $fitfile"
    #input are newimage.cat refusno.cat otcoord.cat,
    #output are match_c.db comp_c.db  nomatch_c.db deltamag_c.db
    	./xcross60cmOT_lc  #need to modified  
  if test ! -s nomatch_c.db
  then
      echo "NO any object is detected in this image"
      xdisplayOTandnewImg
      exit 0
  fi

    mv comp_c.db  $compstarsfile
    mv nomatch_c.db  $OTfile
    mv deltamag_c.db $deltaMagfile 
    
    #===========================
    xgetInfor_OT
    #===========================
}

xmarkRefStarsToimage (  )
{
    :
}


xcrossmatchFor60cmOT(  )  #for the first image
{
    echo "xcrossmatchFor60cmOT"
    cp $OUTPUT_new newimage.cat
    cp $TempUSNOXY refusno.cat
    cp $otxy otcoord.cat

    echo "To get the OT for $fitfile"
    #input are newimage.cat refusno.cat otcoord.cat,
    #output are match_c.db comp_c.db  nomatch_c.db deltamag_c.db
    if [ "$ccd_term"x == "ffov"x   ]
    then
    	./xcross60cmOT
    else
	./xcross60cmOT_jfov
    fi
    mv match_c.db $matchedfile
    mv comp_c.db  $compstarsfile
    mv nomatch_c.db  $OTfile
    mv deltamag_c.db $deltaMagfile 
    echo =========
    cat $OTfile
    echo "======="
    cat  $compstarsfile
    echo "======="
    cat $deltaMagfile
    echo "======="

    if test ! -s $OTfile
    then
        echo "No any new source is detected in the errorbars(errorbars=$serchError pixel)"
	echo "how to report the situation?"
        #exit 0
    else
	echo "@@@@@@@@@@@@@@@@@@"
	wc $OTfile
	delMag_filter=`cat $deltaMagfile | awk '{print($1-$3)}'`
	cat $OTfile | grep "CATAS" >tmpotfile
	#cat $OTfile | grep "newOT" >>tmpotfile
	cat $OTfile | grep  "miniOT"  >tmpotfile1
	cat $OTfile | grep "newOT" >>tmpotfile1
	Notini=`wc tmpotfile1 | awk '{print($1)}'`
	if [ $Notini -lt 1  ]
        then 
            echo "NO miniOT or newOT"
        else
        	cat tmpotfile1 | while read lineot
        	do
        		Not=0
			rm -rf not.txt
        		echo $lineot
                        Rmag_newimage=`echo $lineot | awk '{print($13-delMag_filter)}' delMag_filter=$delMag_filter `
        		xnewotfile=`echo $lineot | awk '{print($1)}'`
        		ynewotfile=`echo $lineot | awk '{print($2)}'`
				
			if [ `echo " $Rmag_newimage < 8.0 " | bc ` -eq 1 ]
			then
				disot2mass_c=7.0
			elif [ `echo " $Rmag_newimage >= 8.0 " | bc ` -eq 1 ]  && [ `echo " $Rmag_newimage < 10.0 " | bc ` -eq 1 ]
			then
				disot2mass_c=4.5
			else
				disot2mass_c=2.5
			fi
			#echo "disot2mass_c=$disot2mass_c"
        		
			cat $Temp2massXY_JKmag | while read line2mass
        		do
        			x2mass=`echo $line2mass | awk '{print($1)}'`
        			y2mass=`echo $line2mass | awk '{print($2)}'`
				Jmag=`echo $line2mass | awk '{print($3)}'`
				Kmag=`echo $line2mass | awk '{print($4)}'`
        		#	echo $xnewotfile $ynewotfile $x2mass $y2mass
        			disot2mass=`echo $xnewotfile $ynewotfile $x2mass $y2mass | awk '{print((($1-$3)^2+($2-$4)^2))^0.5}'`
        			#echo "disot2mass=$disot2mass"
        			if [ ` echo " $disot2mass < $disot2mass_c  " | bc ` -eq 1  ]   # it is successful to match a 2mass object
        			then
        					Not=$(($Not+1))
						echo $Not >not.txt
					#	echo "Not=$Not in the loop"
        					break
        			fi
        		done
			cat not.txt	
			if test ! -s not.txt
        		#if [ "$Not" -lt 1  ]  #no counterpart in the 2mass
        		then
			#	echo "no counterpart" 
        			echo $lineot >>tmpotfile
                        else  #have counterpart in the 2mass
			#	echo "have counterpart"
                                #echo $lineot | sed 's/miniOT/2MASS/g' | sed 's/newOT/2MASS/g' >>tmpotfile
                                #echo $lineot  | sed 's/newOT/2MASS/g' >>tmpotfile
				#xlpxlp  201812144
				xrecheckusno
				if test ! -r xrecheckusno.cat.dis_no   #usno also have one source near the obj
				then
					echo $lineot $magB $magR
					echo "!!!!!!!!!!!!!"
                                	#echo $lineot | sed 's/miniOT/CATAS/g' | sed 's/newOT/CATAS/g' >xcheckmini2catas
					echo $lineot $magB $magR | sed 's/miniOT/CATAS/g' | sed 's/newOT/CATAS/g' | awk '{print($1,$2,$3,$4,$5,$6,$7,$8,$14,$15,$11,$12,$13)}' >>tmpotfile
				fi
        		fi
        	done
       # 	echo "@@@@@@@@@@@@@@@@@@"
        	mv tmpotfile $OTfile
        	wc $OTfile
		cat $OTfile
        fi
	#./xcross2mass
	#output is 2massfile.cat
	#mv 2massfile.cat $OTfile
    fi
    if test ! -s $compstarsfile
    then
        echo "No any useful compstarsfile is found (0.008<merr<0.05, 10:990, 10:990)"
        #exit 0
    else
        #select the top 1 for the check stars. 
        cat $compstarsfile | sort -n -k 3 | head -1 | awk '{print($1,$2,$3,$4,$5,$6,$7,$8,$14,$16,$17,"CHECK",0)}'>>$OTfile
    fi

    cat $compstarsfile | awk '{print($1,$2,$11,$12,$13,$14,$15,$16,$17)}'>$OTFieldTemp   #$1 $2 are the x and y of the image. and others are from catalogues
    cat $OTfile  | awk '{print($1,$2,$12)}' >$OTFieldxy_ref
    cat $OTFieldxy_ref
    cp $TempUSNOXY $OTFieldUSNO
    cp $OTFieldTemp $OTFieldxy $OTFieldxy_ref $OTFieldUSNO $OTTriggerxy $fieldAstrometryCaliFile
   #$OTFieldxy is copied to the $fieldAstrometryCaliFile at the child fluction xUpdateOTtemp
   #===========================
    #xmarkRefStarsToimage
    xgetInfor_OT
    #===========================
}

xrecheckusno ( )
{
	
	echo "xrecheckusno"
	rm -rf xrecheckusno.cat.dis
	xdis_recheckusno=10
	cat $TempUSNOXY	| awk '{if(($1-xnewotfile)>-10 && ($1-xnewotfile)<10 && ($2-ynewotfile)>-10 && ($2-ynewotfile)<10)print($0)}'  xnewotfile=$xnewotfile  ynewotfile=$ynewotfile >xrecheckusno.cat
	if test -s xrecheckusno.cat
	then
		echo "have xrecheckusno.cat"
		rm -rf xrecheckusno.cat.dis_no
		cat xrecheckusno.cat | while read line_recheckusno
		do
			echo $line_recheckusno
			xxx=`echo $line_recheckusno | awk '{print($1)}'`
			yyy=`echo $line_recheckusno | awk '{print($2)}'`
			magB=`echo $line_recheckusno | awk '{print($6)}'`
			magR=`echo $line_recheckusno | awk '{print($8)}'`
			xdis_recheck=`echo $xxx $yyy $xnewotfile $ynewotfile | awk '{print((($1-$3)^2+($2-$4)^2)^0.5)}'` 
			echo $xdis_recheck $xxx $yyy $magB $magR >>xrecheckusno.cat.dis
		done
		cat xrecheckusno.cat.dis | sort -n -k 1 >tmp_xrecheckusno.cat.dis
		mv tmp_xrecheckusno.cat.dis xrecheckusno.cat.dis 
		magB=`cat xrecheckusno.cat.dis | head -1 | awk '{print($4)}' `			
		magR=`cat xrecheckusno.cat.dis | head -1 | awk '{print($5)}' `			
		cat xrecheckusno.cat.dis
		echo "======"
	else
		touch xrecheckusno.cat.dis_no
	fi	


}

xcrossmatchFor60cmOT_ready (   ) #to get the OT and those variables(brighterning or dimming)
{
    #input:  $OUTPUT $TempUSNOXY  $otxy 
    #$OUTPUT parameters: x y mag merr  ellipticity  class_stars fwhm  flag
    #$TempUSNOXY parameters:  x y ra dec B1 B2  R1 R2 I 
    #$otxy parameters: x y ra dec (for OT)

    #output is OT, dimT, picture, Variables catalogues
    
#    rm newimage.cat refusno.cat otcoord.cat match_c.db nomatch_c.db comp_c.db deltamag_c.db
    if test -s $OUTPUT_new
    then
        if test -s $TempUSNOXY
        then
            if test -s $otxy
            then
                xcrossmatchFor60cmOT
            else
                echo "No any source in $otxy, please check the pointing of the telescope"
                echo $Dir_now
                exit 0
            fi
        else
            echo "No any source in $TempUSNOXY, please check the USNO catalog"
            echo $Dir_now
            exit 0
        fi
    else
        echo "No any source in $OUTPUT, bad weather?, shutter closed? mirror closed? dark image? bias images?, dome closed? any other problems?"
        echo $Dir_now
        exit 0
    fi
}

xrecalibrate_to_checkstars ( )
{
#echo "=========before====="
#cat $OTfinalres

filter_d=`cat $OTfinalres | awk '{if($17=="CHECK")print($3)}'`
if [ "$filter_d"x  == "R"x  ]
then
	usnomag=`cat $OTfinalres | awk '{if($17=="CHECK")print($15)}'`
	checkmag=`cat $OTfinalres | awk '{if($17=="CHECK")print($8)}'`
	cat $OTfinalres | grep "CHECK" >tmp
	cat $OTfinalres | grep -v "CHECK" | awk '{print($1,$2,$3,$4,$5,$6,$7,$8-checkmag+usnomag,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20)}' checkmag=$checkmag usnomag=$usnomag  >>tmp
	cat tmp | column -t | grep -v "newOT" | grep -v "2MASS" >$OTfinalres
	rm -rf tmp
elif [ "$filter_d"x == "B"x  ]
then
	usnomag=`cat $OTfinalres | awk '{if($17=="CHECK")print($14)}'`
	checkmag=`cat $OTfinalres | awk '{if($17=="CHECK")print($8)}'`
	cat $OTfinalres | grep "CHECK" >tmp
	cat $OTfinalres | grep -v "CHECK" | awk '{print($1,$2,$3,$4,$5,$6,$7,$8-checkmag+usnomag,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20)}' checkmag=$checkmag usnomag=$usnomag >>tmp
	cat tmp | column -t | grep -v "newOT" | grep -v "2MASS" >$OTfinalres
	rm -rf tmp
else
	cat $OTfinalres | grep -v "newOT" | grep -v "2MASS" >tmp
	mv tmp $OTfinalres
fi
echo "=====after========"
cat $OTfinalres

}

xUploadResult (  )
{
    #OTfinalres
    #other parameters, otid?
    #if $17 is NO_OT, it means that no any new object is detected in this image.
    xrecalibrate_to_checkstars
    echo `pwd`
    if test -r FirstImage.flag
    then
        echo "===have FirstImage.flag"
        rm $fitfile
        cp $OTWCSfit $fitfile
        echo "curl $UploadParameterfile   -F tspname=$FTid   -F followname=$OTid_Follow -F ot2name=$OTid   -F objlist=@$OTfinalres  -F fitsname=@$fitfile  -F limitMag=$limit_mag"
        echo "curl $UploadParameterfile   -F tspname=$FTid   -F followname=$OTid_Follow -F ot2name=$OTid   -F objlist=@$OTfinalres  -F fitsname=@$fitfile  -F limitMag=$limit_mag" >>upload.log
        curl $UploadParameterfile   -F tspname=$FTid   -F followname=$OTid_Follow  -F ot2name=$OTid   -F objlist=@$OTfinalres  -F fitsname=@$fitfile  -F limitMag=$limit_mag
       #curl $UploadParameterfile   -F tspname=$FTid   -F followname=$OTid_Follow  -F ot2name=$OTid   -F objlist=@$OTfinalres  -F fitsname=@$fitfile 
        rm FirstImage.flag
    else
        echo "===No FirstImage.flag"
        #xastronomy_others
        echo "curl $UploadParameterfile   -F tspname=$FTid   -F followname=$OTid_Follow -F ot2name=$OTid   -F objlist=@$OTfinalres  -F fitsname=@$fitfile -F limitMag=$limit_mag"
        echo "curl $UploadParameterfile   -F tspname=$FTid   -F followname=$OTid_Follow -F ot2name=$OTid   -F objlist=@$OTfinalres  -F fitsname=@$fitfile -F limitMag=$limit_mag" >> upload.log
        curl $UploadParameterfile   -F tspname=$FTid  -F followname=$OTid_Follow  -F ot2name=$OTid   -F objlist=@$OTfinalres   -F fitsname=@$fitfile  -F limitMag=$limit_mag
        #curl $UploadParameterfile   -F tspname=$FTid  -F followname=$OTid_Follow  -F ot2name=$OTid   -F objlist=@$OTfinalres   -F fitsname=@$fitfile 

    fi
}

x_xyxymatch_iraf_Tolerence (  )
{
    echo "x_xyxymatch_iraf_Tolerence"
    rm -rf mattmp $OUTPUT_new  transform.db
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    echo noao >> login.cl
    echo digiphot >> login.cl
    echo daophot >>login.cl
    echo "cd $dir_reduction" >> login.cl
    echo flpr >> login.cl
    echo "========"
    echo "xyxymatch(\"outputforxyxymatch\",\"$OTFieldTemp\", \"mattmp\",toleranc=30, xcolumn=1,ycolumn=2,xrcolum=1,yrcolum=2,separation=5, matchin=\"tolerance\", inter-,verbo-) " >>login.cl
   # echo "geomap(\"mattmp\", \"transform.db\", transfo=aa, xmin=1, xmax=2048, ymin=1, ymax=2048,fitgeom=\"general\", functio=\"polynomial\",xxorder=2,xyorder=2,xxterms=\"half\",yxorder=2,yyorder=2,yxterms=\"half\",maxiter=5,reject=3, verbos-, inter-)" >>login.cl
    echo logout >> login.cl
    #cat login.cl
    #cl < login.cl
    cl < login.cl >xlogfile.log 
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    cd $dir_reduction


    echo "mattmp +xyshift0"
    cat mattmp | head -15 >temp1
    sed -n '16,5000p' mattmp | awk '{print($1,$2,$3+xshift0,$4+yshift0,$5,$6)}' xshift0=$xbias yshift0=$ybias | column -t >>temp1
    mv temp1 mattmp


    cd $HOME/iraf
    cp -f login.cl.old login.cl
    echo noao >> login.cl
    echo digiphot >> login.cl
    echo daophot >>login.cl
    echo "cd $dir_reduction" >> login.cl
    echo flpr >> login.cl
    echo "========"
    echo "geomap(\"mattmp\", \"transform.db\", transfo=\"$prefix\", xmin=1, xmax=$CCDsize, ymin=1, ymax=$CCDsize,fitgeom=\"general\", functio=\"polynomial\",xxorder=2,xyorder=2,xxterms=\"half\",yxorder=2,yyorder=2,yxterms=\"half\",maxiter=5,reject=3, verbos-, inter-)" >>login.cl
    echo "geoxytran(\"$OUTPUT\", \"$OUTPUT_new\",\"transform.db\", transfo=\"$prefix\",geometr=\"geometric\",directi=\"backward\",xcolumn=1,ycolumn=2,calctyp=\"double\",min_sig=7)" >>login.cl
    echo "geoxytran(\"$OUTPUT_limit\", \"$OUTPUT_limit_new\",\"transform.db\", transfo=\"$prefix\",geometr=\"geometric\",directi=\"backward\",xcolumn=1,ycolumn=2,calctyp=\"double\",min_sig=7)" >>login.cl
    echo logout >> login.cl
    #cat login.cl
    #cl < login.cl
    cl < login.cl >xlogfile.log 
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    cd $dir_reduction
    if test ! -s transform.db
    then
        echo "No transform.db is produced"
        exit 0
    fi
}

x_xyxymatch_iraf_Triangle (  )
{
    echo "x_xyxymatch_iraf_Triangle"
    rm -rf mattmp $OUTPUT_new  transform.db
    wc outputforxyxymatch 
   wc $OTFieldTemp
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    echo noao >> login.cl
    echo digiphot >> login.cl
    echo daophot >>login.cl
    echo "cd $dir_reduction" >> login.cl
    echo flpr >> login.cl
    echo "xyxymatch(\"outputforxyxymatch\",\"$OTFieldTemp\", \"mattmp\",toleranc=30, xcolumn=1,ycolumn=2,xrcolum=1,yrcolum=2,separation=5, matchin=\"triangles\", inter-,verbo-) " >>login.cl
    echo "geomap(\"mattmp\", \"transform.db\", transfo=\"$prefix\", xmin=1, xmax=\"$CCDsize\", ymin=1, ymax=\"$CCDsize\",fitgeom=\"general\", functio=\"polynomial\",xxorder=2,xyorder=2,xxterms=\"half\",yxorder=2,yyorder=2,yxterms=\"half\",maxiter=1,reject=3, verbos-, inter-)" >>login.cl
    echo "geoxytran(\"$OUTPUT\", \"$OUTPUT_new\",\"transform.db\", transfo=\"$prefix\",geometr=\"geometric\",directi=\"backward\",xcolumn=1,ycolumn=2,calctyp=\"double\",min_sig=7)" >>login.cl
    echo "geoxytran(\"$OUTPUT_limit\", \"$OUTPUT_limit_new\",\"transform.db\", transfo=\"$prefix\",geometr=\"geometric\",directi=\"backward\",xcolumn=1,ycolumn=2,calctyp=\"double\",min_sig=7)" >>login.cl
    echo logout >> login.cl
   # cl < login.cl
    cl < login.cl >xlogfile.log 
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    cd $dir_reduction
    if test ! -s transform.db
    then
        echo "No transform.db is produced"
        exit 0
    fi 
    sleep 10
}

ximagetranserwithwcs ( )
{
    echo "ximagetranserwithwcs"
    echo "fitfile"
    echo "OTWCSfit"
    #echo $OUTPUT | awk '{print($1,$2)}' >outputxy
    echo "1028 1028" >xycenter
    xy2sky -d $fitfile @xycenter >xycenterwcs
    sky2xy $OTWCSfit @xycenterwcs | awk '{print($5,$6)}' >xycenterwcsxy
    xnew=`cat xycenter | awk '{print($1)}'`
    ynew=`cat xycenter | awk '{print($2)}'`
    xtemp=`cat xycenterwcsxy | awk '{print($1)}'`
    ytemp=`cat xycenterwcsxy | awk '{print($2)}'`
    xbias=`echo $xnew $xtemp | awk '{print($1-$2)}'`
    ybias=`echo $ynew $ytemp | awk '{print($1-$2)}'`
   echo "xbias=$xbias ybias=$ybias"

}




x_xyxymatch (  )
{
    echo "===========x_xyxymatch==========="
    echo $OUTPUT_new $OTFieldTemp
    xastronomy_others 
    ximagetranserwithwcs
    cat $OUTPUT | awk '{if($4<0.05)print($1-xbias,$2-ybias)}' xbias=$xbias ybias=$ybias >outputforxyxymatch
    wc -l outputforxyxymatch
    N_OTfieldTemp=`cat $OTFieldTemp | wc -l | awk '{print($1)}'`
    if [ $N_OTfieldTemp -gt 4 ]
    then
        #x_xyxymatch_iraf_Triangle
        x_xyxymatch_iraf_Tolerence
    else
        x_xyxymatch_iraf_Tolerence
    fi
   
    rm outputforxyxymatch
    cat transform.db | grep "shift" | tail -2
    cat transform.db | grep "rms" | tail -2
    xrms=`cat transform.db | grep "rms" | tail -2 | tr '\n' ' ' | awk '{print($2)}'`
    yrms=`cat transform.db | grep "rms" | tail -2 | tr '\n' ' ' | awk '{print($4)}'`
    xshift=`cat transform.db | grep "shift" | tail -2 | tr '\n' ' ' | awk '{print($2)}'`
    yshift=`cat transform.db | grep "shift" | tail -2 | tr '\n' ' ' | awk '{print($4)}'`
    echo "xrms=$xrms yrms=$yrms xshift=$xshift yshift=$yshift" >>$Monitorfile
    #cat $OUTPUT_new
    if [ ` echo " $xrms > 1.5 " | bc ` -eq 1  ]  ||  [ ` echo " $yrms > 1.5 " | bc ` -eq 1  ] 
    then
        echo "xyxymatch failed, try next image"
        exit 0
    else
        echo "xyxymatch success"
        #=============================
        xcrossmatchFor60cmOT_lc
        #=============================
    fi
}



xcopyTempAndReduc (  )
{
    echo "xcopyTempAndReduc"
    cd  $fieldAstrometryCaliFile
    cp $OTFieldTemp $OTTriggerxy $OTFieldxy $OTFieldxy_ref $OTWCSfit $OTFieldUSNO $Temp2massXY_JKmag $Temp2massXY_Jmag $Temp2massXY_Kmag $dir_reduction
    cd $dir_reduction
    N_compstars=`cat $OTFieldTemp | wc -l | awk '{print($1)}'`
    echo $N_compstars
    if [ $N_compstars -lt $Ncompstar_c  ]  #comparison stars as a reference stars for xyxymatch should not be smaller than 3
    then
        echo "The number of comparison stars is too smaller"
        cat $OTFieldUSNO | awk '{if($8<18 && $8>0)print($0)}' | sort -n -k 8 | head -10 > $OTFieldTemp
        cat $OTFieldTemp 
        wc -l $OTFieldTemp
        echo "@@@@@@@@@@@@@@@@@@@@@@"
        cp $OTFieldTemp $fieldAstrometryCaliFile
    fi
    x_xyxymatch
}

xmkFirstimage (  )
{
    cd $dir_reduction
    echo "xmkFirstimage"
    touch FirstImage.flag
    ls FirstImage.flag
    xastronomy
    #xGetCatalog
    xGetCatalog_temp
    xGetCatalog_temp_2mass
    xsky2xyTemp
    xsky2xyTemp_2mass
    xsky2xyOT
    xcrossmatchFor60cmOT_ready
}

xcheckimage (  )
{
    echo "xcheckimage"
    #to check if this field has been astrometrical calibrated or not?
    #if yes, copy the related files and then get the light curve.
    #if not, to make the calibration first by the function xmkFirstimage
    
    cd $fieldAstrometryCaliFile
    if [ -r $OTFieldTemp ] && [ -r $OTFieldxy ]  && [ -r $OTWCSfit   ]
    then
        echo "This field have calibrated fiels"
        xcopyTempAndReduc
    else
        echo `pwd`
        echo "New field, to Astrometry calibration first"
        xmkFirstimage

    fi
}
#xsethead
xGetkeywords
xdefineForFits
xdefineForCatalog
xGetstars
xcheckimage
xdisplayOTandnewImg
sleep 0.1
cd $Dir_now
